import React, {useEffect} from 'react';
import {
    Alert, BackHandler,
    Dimensions,
    Image, Keyboard,
    SafeAreaView,
    TextInput,
    ToastAndroid,
    TouchableOpacity,
    TouchableWithoutFeedback,
    View
} from "react-native";
import { StyleSheet } from 'react-native';
import {
    Button,
    Card,
    Divider,
    Icon,
    Input,
    Layout, List,
    Tab,
    TabView,
    Text,
    TopNavigation,
    TopNavigationAction
} from '@ui-kitten/components';
import SorageManager from "../Compoments/SorageManager";
import AsyncStorage from "@react-native-async-storage/async-storage";

const data = new Array(8).fill({
    title: 'Item',
});



export const ItemTestScreen = ({ navigation }) => {


    const [unPassList, setUnPassList] = React.useState([]);
    const [passList, setPassList] = React.useState([]);



    /**
     *获取为通过的列表
     */
    const  getUnPassList=(jrd,rkid)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

        fetch("http://htjoa.nrnet.cn/dc14/jwmis/LivingItem/u?jrd="+jrd+"&rkid="+rkid, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"获取未通过列表")
                setUnPassList(result)
            })
            .catch(error => console.log('error', error));
    }

    /**
     *获取已通过的列表
     */
    const getPassList=(jrd,rkid)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

        fetch("http://htjoa.nrnet.cn/dc14/jwmis/LivingItem/qualityAdopt?jrd="+jrd+"&rkid="+rkid, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,'获取已通过的列表')
                setPassList(result)
            })
            .catch(error => console.log('error', error));

    }

    /**
     *通过 按钮
     */
    const checkPass=(hxtqr,id,belongduan,rkid)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        const url = "http://htjoa.nrnet.cn/dc14/jwmis/acceptancerepair/repaircrossbyid?ysr="+hxtqr+"&id="+id+"&rkid="+rkid+"&jrd="+belongduan
        console.log(url)
        fetch(url, requestOptions)
            .then(response => response.text())
            .then(result => {
                console.log(result,"点击了已通过")
                if (result === 'success'){
                    showToast("提交成功")
                    getUnPassList(belongduan,'')

                }else
                {showToast("遇到问题，该活项 已被操作请刷新页面")}

            })
            .catch(error => console.log('error', error));
    }

    /**
     * 未通过 按钮
     */
    const checkUnPass= (hxtqr,id,belongduan,rkid)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        const url = "http://htjoa.nrnet.cn/dc14/jwmis/acceptancerepair/repairfailbyid?ysr="+hxtqr+"&id="+id+"&rkid="+rkid +"&jrd="+belongduan
       console.log(url)
        fetch(url, requestOptions)
            .then(response => response.text())
            .then(async result => {
                console.log(result, "未通过按钮")
                if (result === "success") {
                    showToast("提交成功")
                    const s = await AsyncStorage.getItem("search3")
                    if (s === undefined || s === null) {
                        getUnPassList(belongduan, '')
                    } else {
                        getUnPassList(belongduan, s)
                    }

                } else {
                    showToast("遇到问题，该活项 已被操作请刷新页面")
                }
            })
            .catch(error => console.log('error', error));
    }

    useEffect(()=>{

        //首次进入删除search
        SorageManager.set("search3",'')

        Keyboard.addListener("keyboardDidHide", _keyboardDidHide);


        SorageManager.get('userInf').then(r =>{
            SorageManager.get("search3").then(s=>{
                console.log(r,"userINf")
                if(s === undefined || s === null){
                    getUnPassList(r["belongduan"],'')
                    getPassList(r["belongduan"],"")
                }
                else {
                    getUnPassList(r["belongduan"],s)
                    getPassList(r["belongduan"],s)
                }
            })
        } )


        // cleanup function
        return () => {
            Keyboard.removeListener("keyboardDidHide", _keyboardDidHide);
        };

    },[])


    //监听键盘事件，缩回根据 搜索框内容重新加载
    const _keyboardDidHide = () => {
        console.log(value)
        SorageManager.get('userInf').then(async r => {
            const s = await AsyncStorage.getItem("search3")
            console.log(s)
            if (s === undefined || s === null) {
                getUnPassList(r["belongduan"], '')
                getPassList(r["belongduan"], "")
            } else {
                getUnPassList(r["belongduan"], s)
                getPassList(r["belongduan"], s)
            }

        })

    };

    const navigateAddTicketCollection = () => {
        navigation.navigate('AddTicketCollection');
    };



    const renderItemHeader = (headerProps,info) => (
        <View {...headerProps} style={{alignItems: 'center',margin:10}}>
            <Text category='h6' >
                车型： {info.item.firstname}        车号： {info.item.ch}
            </Text>
        </View>
    );

    const renderItemFooter = (footerProps,info) => (
        <Layout style={{flexDirection:"row",alignItems: 'center', justifyContent:'space-evenly'
        }}>

            <Button appearance='outline' status='warning' onPress={()=>{
                SorageManager.get('userInf').then(r =>{
                    console.log(r,"userINF")
                    checkUnPass(r["userid"],info.item.id,r["belongduan"],info.item.RKID)


                })



               }} >
                未通过
            </Button>

            <Button onPress={()=>{
                SorageManager.get('userInf').then(r =>{
                    console.log(r,"userINF")
                    console.log(info.item.RKID)
                    checkPass(r["userid"],info.item.id,r["belongduan"],info.item.RKID)
                } )
                }} >
                通过
            </Button>

        </Layout>

    );

    const renderItem = (info) => (
        <Card
            style={styles.item}
            status='basic'
            header={headerProps => renderItemHeader(headerProps, info)}
            footer={footerProps =>renderItemFooter(footerProps,info)}>
            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        领取时间: {info.item.wxlqrq}
                    </Text>
                </Layout>

                {/*<Layout style={styles.textItem}>*/}
                {/*    <Text>*/}
                {/*        范围:0*/}
                {/*    </Text>*/}
                {/*</Layout>*/}
                {/*<Layout style={styles.textItem}>*/}
                {/*    <Text>*/}
                {/*        动态:0*/}
                {/*    </Text>*/}
                {/*</Layout>*/}
            </Layout>


            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        股道:{info.item.gdsw}
                    </Text>
                </Layout>

                <Layout style={styles.textItem}>
                    <Text>
                        提票人:{info.item.wxtqrhz}
                    </Text>
                </Layout>
            </Layout>


            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        领活时间:{info.item.wxlqrq}
                    </Text>
                </Layout>
            </Layout>
            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        完成时间: {info.item.wxwcrq}
                    </Text>
                </Layout>

                {/*<Layout style={styles.textItem}>*/}
                {/*    <Text>*/}
                {/*        范围:0*/}
                {/*    </Text>*/}
                {/*</Layout>*/}
                {/*<Layout style={styles.textItem}>*/}
                {/*    <Text>*/}
                {/*        动态:0*/}
                {/*    </Text>*/}
                {/*</Layout>*/}
            </Layout>

            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        故障名称：
                    </Text>
                </Layout>
                <Layout style={styles.textItem}>
                    <Text>
                        {info.item.gzxx}
                    </Text>
                </Layout>

                {/*<Layout style={styles.textContainer}>*/}
                {/*    <Layout style={styles.textItem}>*/}
                {/*        <Text>*/}
                {/*            维修方式:{info.item.}*/}
                {/*        </Text>*/}
                {/*    </Layout>*/}
                {/*</Layout>*/}



            </Layout>



        </Card>
    );


    const accept = (info) => (
        <Card
            style={styles.item}
            status='success'
            header={headerProps => renderItemHeader(headerProps, info)}
        >


            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        股道:{info.item.rgd}
                    </Text>
                </Layout>

                <Layout style={styles.textItem}>
                    <Text>
                        提票人:{info.item.wxtqrhz}
                    </Text>
                </Layout>
            </Layout>


            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        领活时间:{info.item.wxlqrq}
                    </Text>
                </Layout>
            </Layout>
            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        完成时间: {info.item.wxwcrq}
                    </Text>
                </Layout>

                {/*<Layout style={styles.textItem}>*/}
                {/*    <Text>*/}
                {/*        范围:0*/}
                {/*    </Text>*/}
                {/*</Layout>*/}
                {/*<Layout style={styles.textItem}>*/}
                {/*    <Text>*/}
                {/*        动态:0*/}
                {/*    </Text>*/}
                {/*</Layout>*/}
            </Layout>

            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        故障名称：
                    </Text>
                </Layout>
                <Layout style={styles.textItem}>
                    <Text>
                        {info.item.gzxx}
                    </Text>
                </Layout>
            </Layout>


        </Card>
    );



    const renderacceptFooter = (footerProps) => (
        <Button appearance='outline' status='warning' onPress={deleteButton}>
            取消
        </Button>
    );


    // const BackIcon = (props) => (
    //     <Icon {...props} name='arrow-back' />
    // );
    // const navigateBack = () => {
    //     navigation.goBack();
    // };
    // const BackAction = () => (
    //     <TopNavigationAction icon={BackIcon} onPress={navigateBack}/>
    // );







    const BackIcon = (props) => (
        <Icon {...props} name='arrow-back'/>
    );

    const navigateMenu = () => {
        navigation.navigate('Menu');
    };

    const BackAction = () => (
        <TopNavigationAction icon={BackIcon} onPress={navigateMenu}/>
    );

    const showToast = (message) => {
        ToastAndroid.show(message, ToastAndroid.SHORT);
    };

    const [selectedIndex, setSelectedIndex] = React.useState(0);
    const [value, setValue] = React.useState('');
    return (
        <View style={{ flex: 1 }}>
            <TopNavigation
                accessoryLeft={BackAction}

                title='活项检验' alignment='center' />
            <Divider/>
            <TabView
                selectedIndex={selectedIndex}
                onSelect={index => {setSelectedIndex(index)
                    SorageManager.get('userInf').then(async r => {
                        const s = await AsyncStorage.getItem("search3")
                        console.log(s)
                        if (s === undefined || s === null) {
                            getUnPassList(r["belongduan"], '')
                            getPassList(r["belongduan"], "")
                        } else {
                            getUnPassList(r["belongduan"], s)
                            getPassList(r["belongduan"], s)
                        }
                    })
                }}>
                <Tab title='未通过'>
                    <Layout style={styles.tabContainer}>


                        <View style={{flexDirection:'row',justifyContent: 'center',marginTop:10,marginBottom:10}}>

                            <Input
                                onSubmitEditing={Keyboard.dismiss}
                                style={{width:Dimensions.get('window').width-20}}
                                value={value}
                                placeholder='机车号模糊查找'
                                accessoryRight={(<Icon
                                    onPress={()=>{

                                        SorageManager.get('userInf').then(r =>{

                                                console.log(r,"userINf")
                                                getUnPassList(r["belongduan"],'')
                                                getPassList(r["belongduan"],"")
                                                SorageManager.set("search3", '')
                                                ToastAndroid.show("取消查询", ToastAndroid.SHORT);
                                                setValue('')
                                            })

                                    }}
                                    style={styles.icon}
                                    fill='#8F9BB3'
                                    name='close-outline'
                                />)}
                                // secureTextEntry={secureTextEntry}
                                onChangeText={async nextValue => {
                                    setValue(nextValue);
                                    await AsyncStorage.setItem("search3", nextValue)
                                }}
                            />

                            {/*<Input*/}
                            {/*       placeholder='机车号'*/}
                            {/*       value={value}*/}
                            {/*       onChangeText={nextValue => setValue(nextValue)}>*/}
                            {/*</Input>*/}

                        </View>

                        <Divider/>
                        <List
                            style={styles.container}
                            contentContainerStyle={styles.contentContainer}
                            data={unPassList}
                            renderItem={renderItem}
                        />

                    </Layout>
                </Tab>

                <Tab title='已通过'>
                    <Layout style={styles.tabContainer}>
                        <List
                            style={styles.container}
                            contentContainerStyle={styles.contentContainer}
                            data={passList}
                            renderItem={accept}
                        />

                    </Layout>
                </Tab>
            </TabView>

        </View>
    );
};

const styles = StyleSheet.create({
    container: {

    },
    contentContainer: {
        paddingHorizontal: 15,
        // paddingVertical: 4,
    },
    item: {
        marginTop:15,
        // marginVertical: 4,

    },

    tabContainer: {
        height: Dimensions.get('window').height-118,
    },

    textContainer:{
        flexDirection:'row',
        flexWrap:'wrap',
        justifyContent:"space-evenly",
        alignItems:"center",
        marginBottom:10

    },
    textItem:{
        justifyContent:'center',
        alignItems:'center',

    }
});